<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>

  <body>
    <script>
      // Part 1111111
      //分析控制台输出结果
      console.log(1);
      //Promise 构造函数执行时立即调用执行 executor 函数
      new Promise(function (resolve, reject) {
        console.log(2);//同步任务
      });
      setTimeout(function () {
        console.log(3);
      }, 0);
      console.log(4);

      // Part 2222222
      //分析控制台输出结果
      console.log(1);
      //Promise 构造函数执行时立即调用执行 executor 函数
      let promise= new Promise(function (resolve, reject) {
        console.log(2);//同步任务
        setTimeout(function(){
          resolve("可传递任意类型的数据");//
          console.log("查看promise状态2:",promise);
        }, 3000);
      });
      setTimeout(function () {
        console.log(3);
      }, 0);
      console.log(4);
      console.log("查看promise状态1:",promise);

      //查看后续案例，掌握then方法
      promise.then((data)=>{console.log(data)},(err)=>{});

      ///////补充案例：理解promise对象的状态
      var p1 = new Promise((resolve, reject) => {
        resolve(1);
      });
      p1.then((data) => {
        console.log(data);
        return 2;
      }).then((data) => {
        console.log(data);
        setTimeout(()=>{return 3;},2000);
      }).then((data) => {
        console.log(data);
      });
      //思考：上述案例最后的then能否输出3？undefined

      //下述代码是如何通过返回新promise对象来实现
      var p2 = new Promise((resolve, reject) => {
        resolve(1);
      });
      p2.then((data) => {
        console.log(data);
        return 2;
      }).then((data) => {
        console.log(data);
        return new Promise((resolve,reject)=>{setTimeout(()=>{resolve(3);},2000)})
      }).then((data) => {
        console.log(data);
      });
      
      
      
      var p2 = new Promise((resolve, reject) => {
        setTimeout(()=>{resolve(1);},3000)
      });
      p2.then((data) => {
        console.log(data);
        return 2;
      }).then((data) => {
        console.log(data);
        return new Promise((resolve,reject)=>{setTimeout(()=>{resolve(3);},2000)})
      }).then((data) => {
        console.log(data);
      });
      // 3s后 1 2 2s后 3
      </script>
  </body>
</html>
